package it.slkfarm.android;

import it.slkfarm.adapter.CropAdapter;
import it.slkfarm.bean.Crop;
import it.slkfarm.bean.Farm;
import it.slkfarm.bean.Production;
import it.slkfarm.drawable.CustomShapeDrawable;
import it.slkfarm.helpers.DialogBuilder;
import it.slkfarm.log.LogData;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;



import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CropList extends Base implements OnClickListener 
{
	/**
	 * @uml.property  name="listView"
	 * @uml.associationEnd  
	 */
	private ListView listView;
	/**
	 * @uml.property  name="cropList"
	 * @uml.associationEnd  multiplicity="(0 -1)" elementType="it.slkfarm.bean.Crop"
	 */
	private List<Crop> cropList;
	/**
	 * @uml.property  name="cropView"
	 */
	private List<Crop> cropView;
	/**
	 * @uml.property  name="back"
	 * @uml.associationEnd  
	 */
	private Button back;
	/**
	 * @uml.property  name="pkg"
	 */
	private String pkg = "";
	/**
	 * @uml.property  name="production"
	 * @uml.associationEnd  
	 */
	private Production production;
	/**
	 * @uml.property  name="farm"
	 * @uml.associationEnd  
	 */
	private Farm farm;
	/**
	 * @uml.property  name="type"
	 */
	private String type;
	/**
	 * @uml.property  name="search"
	 * @uml.associationEnd  
	 */
	private EditText search;
	/**
	 * @uml.property  name="tf"
	 * @uml.associationEnd  
	 */
	private Typeface tf;
	/**
	 * @uml.property  name="layout"
	 * @uml.associationEnd  
	 */
	private RelativeLayout layout;
	/**
	 * @uml.property  name="builder"
	 * @uml.associationEnd  
	 */
	private DialogBuilder builder;
	/**
	 * @uml.property  name="lang"
	 */
	private int lang;
	/**
	 * @uml.property  name="toast"
	 * @uml.associationEnd  
	 */
	private Toast toast;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState)  
	{
		super.onCreate(savedInstanceState);
		Log.i("croplist", "create");
		setLanguage(dbAdapter.getSetLanguage());
		lang = dbAdapter.getSetLanguage();
		builder = new DialogBuilder(this, lang);
		setContentView(R.layout.crop_list);
		layout = new RelativeLayout(this);
		pkg = getPackageName();
		production = ((CropTabView)this.getParent()).getProduction();
		farm = production.getFarm();
		type = getIntent().getStringExtra(pkg + ".type");
		cropList = dbAdapter.getCropsList(farm.getAgroGeolocigalRegionId(), type);
		listView = (ListView) findViewById(R.id.cropListView);
		listView.setItemsCanFocus(true);
		listView.setOnItemClickListener(new OnItemClickListener() 
		{

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
			{
				Log.i("list", "click");
				Crop c = (Crop) listView.getAdapter().getItem(arg2);
				int prodId = dbAdapter.getProductionId(c.getCultivarId(), c.getCropId(), farm.getId());
				if (prodId == -1)
				{
					if (!production.isCropPresent(c))
					{
						LogData log = new LogData("CropList","ListView","Crop selected: "+c.getCropName() + " " +c.getCultivarName());
						logger.appendLog(log);
						c.setSelected(true);
						c.setProductionId(-1);
						production.addCrop(c);
						String message = c.getCropName() + " " + " (" + c.getCultivarName()+") " + getResources().getString(R.string.selected) ;
						Toast t = builder.createToast(0, message, CropList.this);
						t.show();
						RoundRectShape rs = new RoundRectShape(new float[] { 7, 7, 7, 7, 7, 7, 7, 7 }, null, null);
					    ShapeDrawable sd = new CustomShapeDrawable(rs, c.getPercentageProduction(), 5, true);
					    arg1.setBackgroundDrawable(sd);
					}	
					else
					{
						LogData log = new LogData("CropList","ListView","Crop unselected: "+c.getCropName() + " " +c.getCultivarName());
						logger.appendLog(log);
						c.setSelected(false);
						c.setQuantity(0);
						production.removeCrop(c);
						String message = c.getCropName() + " " + " (" + c.getCultivarName()+") " + getResources().getString(R.string.unselected) ;
						Toast t = builder.createToast(0, message, CropList.this);
						t.show();
						RoundRectShape rs = new RoundRectShape(new float[] { 7, 7, 7, 7, 7, 7, 7, 7 }, null, null);
					    ShapeDrawable sd = new CustomShapeDrawable(rs, c.getPercentageProduction(), 5, false);
					    arg1.setBackgroundDrawable(sd);
					}
				}
				else
				{
					LogData log = new LogData("CropList","ListView","Crop already in production: "+c.getCropName() + " " +c.getCultivarName());
					logger.appendLog(log);
					toast = builder.createToast(R.string.nounselect, null, CropList.this);
					toast.show();
				}
				
			}
		});
		back = (Button) findViewById(R.id.btnCropListBack);
		back.setOnClickListener(this);
		tf = getTypeface();
		back.setTypeface(tf);
		production.setCropSelection(dbAdapter.getProductionList(farm.getId()));
		Log.i("production", String.valueOf(production.getCropSelection().size()));
		setSelected();
		cropView = cropList;
		search = (EditText) findViewById(R.id.editSearch);
		search.setTypeface(tf);
		search.addTextChangedListener(new TextWatcher() 
		{
			public void onTextChanged(CharSequence s, int start, int before, int count) 
			{	
				cropView = new ArrayList<Crop>();
				for(int i=0; i<cropList.size();i++)
				{
					if (cropList.get(i).getCultivarName().toLowerCase().contains(s.toString().toLowerCase()) || cropList.get(i).getCropName().toLowerCase().contains(s.toString().toLowerCase()))
						cropView.add(cropList.get(i));
				}
				LogData log = new LogData("CropList","Seach","Crop search: "+s.toString());
				logger.appendLog(log);
				loadList();
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count, int after) 
			{

			}
			
			public void afterTextChanged(Editable s) 
			{
				
			}
		});
		loadList();
	}
	
	public void setSelected()
	{
		for (int i=0; i<cropList.size(); i++)
		{
			if (production.isCropPresent(cropList.get(i)))
				cropList.get(i).setSelected(true);
			else
				cropList.get(i).setSelected(false);
		}
	}
	 
	private void loadList()
	{
		if (cropView.size() > 0)
		{
			listView.setVisibility(View.VISIBLE);
			layout.setVisibility(View.GONE);
			listView.setAdapter(new CropAdapter(this, R.layout.crop_row, cropView, false, dbAdapter.getSetLanguage()));
			
		}	
		else
		{
			listView.setVisibility(View.GONE);
			layout.setVisibility(View.VISIBLE);
			layout.removeAllViews();
			RelativeLayout parent = (RelativeLayout) findViewById(R.id.layoutCropList);
			parent.removeView(layout);
			RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			layout.setGravity(Gravity.CENTER_HORIZONTAL);
			TextView tv = new TextView(this);
			tv.setText(R.string.nullCrop);
			tv.setTextColor(Color.parseColor("#43520B"));
			tv.setTypeface(tf);
			layout.addView(tv);
			RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			params2.addRule(RelativeLayout.BELOW, search.getId());
			parent.addView(layout, params2);		
		}
	}
	
	public void onResume()
	{
		super.onResume();
		production = ((CropTabView)this.getParent()).getProduction();
		setSelected();
		loadList();
		cropView = cropList;
	}
	
	public void onClick(View v) 
	{
		LogData log = new LogData("CropList","Button back","Back to menu");
		logger.appendLog(log);
		finish();
	}
	
}


